package demo;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

import org.apache.maven.model.Dependency;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;

public class PomParser {

  public static void main(String[] args) {
    String directoryPath = "/Users/fudongming/Projects/tongbaninfo/project_back_sh_ybsl"; // 替换为实际的目录路径
    String excelFilePath = "output.xlsx"; // 替换为实际的输出 Excel 文件路径

    try {
      // 递归查找所有 pom.xml 文件并解析依赖
      List<Dependency> allDependencies = findAndParsePomFiles(directoryPath);

      // 导出为 Excel 文件
      exportToExcel(allDependencies, excelFilePath);

      System.out.println("依赖信息已成功导出到 " + excelFilePath);
    } catch (IOException | XmlPullParserException e) {
      e.printStackTrace();
    }
  }

  /**
   * 递归查找指定目录及其子目录下的所有 pom.xml 文件，并解析依赖
   * @param directoryPath 目录路径
   * @return 所有依赖列表
   * @throws IOException
   * @throws XmlPullParserException
   */
  public static List<Dependency> findAndParsePomFiles(String directoryPath) throws IOException, XmlPullParserException {
    List<Dependency> allDependencies = new ArrayList<>();
    File directory = new File(directoryPath);
    if (!directory.exists() || !directory.isDirectory()) {
      throw new IllegalArgumentException("指定的路径不是一个有效的目录: " + directoryPath);
    }

    File[] files = directory.listFiles();
    if (files != null) {
      for (File file : files) {
        if (file.isDirectory()) {
          // 跳过 src 和 target 目录
          if ("src".equals(file.getName()) || "target".equals(file.getName())) {
            continue;
          }
          // 递归处理子目录
          allDependencies.addAll(findAndParsePomFiles(file.getAbsolutePath()));
        } else if (file.getName().equals("pom.xml")) {
          // 解析 pom.xml 文件
          allDependencies.addAll(parsePomFile(file.getAbsolutePath()));
        }
      }
    }
    return allDependencies;
  }

  /**
   * 解析 pom.xml 文件，获取依赖信息
   * @param pomFilePath pom.xml 文件的路径
   * @return 依赖列表
   * @throws IOException
   * @throws XmlPullParserException
   */
  public static List<Dependency> parsePomFile(String pomFilePath) throws IOException, XmlPullParserException {
    File pomFile = new File(pomFilePath);
    if (!pomFile.exists()) {
      throw new FileNotFoundException("pom.xml 文件未找到: " + pomFilePath);
    }

    MavenXpp3Reader reader = new MavenXpp3Reader();
    Model model = reader.read(new FileReader(pomFile));
    return model.getDependencies();
  }

  /**
   * 将依赖信息导出为 Excel 文件
   * @param dependencies 依赖列表
   * @param excelFilePath 输出 Excel 文件的路径
   * @throws IOException
   */
  public static void exportToExcel(List<Dependency> dependencies, String excelFilePath) throws IOException {
    Workbook workbook = new XSSFWorkbook();
    Sheet sheet = workbook.createSheet("Dependencies");

    // 创建表头
    Row headerRow = sheet.createRow(0);
    String[] headers = {"Group ID", "Artifact ID", "Version"};
    for (int i = 0; i < headers.length; i++) {
      Cell cell = headerRow.createCell(i);
      cell.setCellValue(headers[i]);
    }

    // 填充数据
    for (int i = 0; i < dependencies.size(); i++) {
      Dependency dependency = dependencies.get(i);
      Row row = sheet.createRow(i + 1);

      Cell groupIdCell = row.createCell(0);
      groupIdCell.setCellValue(dependency.getGroupId());

      Cell artifactIdCell = row.createCell(1);
      artifactIdCell.setCellValue(dependency.getArtifactId());

      Cell versionCell = row.createCell(2);
      versionCell.setCellValue(dependency.getVersion());
    }

    // 调整列宽
    for (int i = 0; i < headers.length; i++) {
      sheet.autoSizeColumn(i);
    }

    // 写入文件
    try (FileOutputStream fileOut = new FileOutputStream(excelFilePath)) {
      workbook.write(fileOut);
    } finally {
      workbook.close();
    }
  }
}